// 简化的模型体验模态框
let currentModelType = null;

// 模型配置
const modelConfigs = {
    'rf': {
        name: '随机森林模型',
        description: '基于多决策树的集成学习算法，具有良好的鲁棒性和预测准确度。',
        endpoint: '/api/predict-rf'
    },
    'xgb': {
        name: 'XGBoost模型',
        description: '基于梯度提升的高效机器学习算法，在房间占用预测任务中表现优异。',
        endpoint: '/api/predict-xgb'
    },
    'lstm': {
        name: 'LSTM神经网络',
        description: '长短期记忆网络，专门处理时序数据，能够捕捉房间占用的时间模式。',
        endpoint: '/api/predict-lstm'
    },
    'ensemble': {
        name: '集成模型',
        description: '融合随机森林、XGBoost和LSTM三种模型的预测结果，通过集成学习提供更准确的预测。',
        endpoint: '/api/predict-ensemble'
    }
};

// 预设数据
const presetData = {
    morning: {
        temp1: 22.5, temp2: 22.2, temp3: 22.8, temp4: 22.4,
        light1: 450, light2: 520, light3: 480, light4: 460,
        sound1: 0.08, sound2: 0.12, sound3: 0.06, sound4: 0.10,
        co2: 450, pir: 2.5, hour: 9, occupancy: 1
    },
    afternoon: {
        temp1: 24.8, temp2: 24.5, temp3: 25.1, temp4: 24.7,
        light1: 680, light2: 750, light3: 720, light4: 690,
        sound1: 0.15, sound2: 0.18, sound3: 0.12, sound4: 0.16,
        co2: 520, pir: 4.2, hour: 14, occupancy: 1
    },
    evening: {
        temp1: 23.2, temp2: 23.0, temp3: 23.5, temp4: 23.1,
        light1: 200, light2: 180, light3: 220, light4: 195,
        sound1: 0.05, sound2: 0.04, sound3: 0.06, sound4: 0.05,
        co2: 380, pir: 1.8, hour: 19, occupancy: 0
    }
};

// 初始化函数
function initModelExperienceModal() {
    console.log('模型体验模态框初始化');
    
    // 设置全局变量
    window.ModelExperienceModal = {
        open: openModalDirectly
    };
    
    // 添加事件监听
    const modal = document.getElementById('modelExperienceModal');
    if (modal) {
        // 点击外部关闭
        modal.addEventListener('click', function(e) {
            if (e.target === modal) {
                closeModelModal();
            }
        });
        
        // ESC键关闭
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && modal.classList.contains('show')) {
                closeModelModal();
            }
        });
    }
    
    console.log('模型体验模态框初始化完成');
}

// 直接打开模态框
function openModalDirectly(modelType) {
    console.log('打开模型体验模态框:', modelType);
    
    currentModelType = modelType;
    const modal = document.getElementById('modelExperienceModal');
    const config = modelConfigs[modelType];
    
    if (!modal || !config) {
        console.error('模态框或配置不存在');
        return;
    }
    
    // 更新模型信息
    const nameElement = document.getElementById('modelName');
    const descElement = document.getElementById('modelDescription');
    
    if (nameElement) nameElement.textContent = config.name;
    if (descElement) descElement.textContent = config.description;
    
    // 清空表单和结果
    clearForm();
    hideResult();
    
    // 显示模态框
    modal.classList.add('show');
    document.body.style.overflow = 'hidden';
}

// 关闭模态框
function closeModelModal() {
    const modal = document.getElementById('modelExperienceModal');
    if (modal) {
        modal.classList.remove('show');
        document.body.style.overflow = '';
        currentModelType = null;
    }
}

// 加载预设数据
function loadPresetData(presetType) {
    let data;
    
    if (presetType === 'random') {
        data = generateRandomData();
    } else {
        data = presetData[presetType];
    }
    
    if (!data) {
        console.error(`预设数据类型 ${presetType} 不存在`);
        return;
    }
    
    // 填充表单
    Object.keys(data).forEach(key => {
        const element = document.getElementById(key);
        if (element) {
            element.value = data[key];
        }
    });
    
    console.log(`加载${presetType}预设数据完成`);
}

// 生成随机数据
function generateRandomData() {
    return {
        temp1: (20 + Math.random() * 8).toFixed(1),
        temp2: (20 + Math.random() * 8).toFixed(1),
        temp3: (20 + Math.random() * 8).toFixed(1),
        temp4: (20 + Math.random() * 8).toFixed(1),
        light1: Math.floor(100 + Math.random() * 800),
        light2: Math.floor(100 + Math.random() * 800),
        light3: Math.floor(100 + Math.random() * 800),
        light4: Math.floor(100 + Math.random() * 800),
        sound1: (Math.random() * 0.2).toFixed(3),
        sound2: (Math.random() * 0.2).toFixed(3),
        sound3: (Math.random() * 0.2).toFixed(3),
        sound4: (Math.random() * 0.2).toFixed(3),
        co2: Math.floor(350 + Math.random() * 400),
        pir: (Math.random() * 5).toFixed(1),
        hour: Math.floor(Math.random() * 24),
        occupancy: Math.floor(Math.random() * 2)
    };
}

// 清空表单
function clearForm() {
    const inputs = document.querySelectorAll('#modelExperienceModal input[type="number"]');
    inputs.forEach(input => {
        input.value = '';
    });
}

// 收集表单数据
function collectFormData() {
    const data = {};
    const inputs = document.querySelectorAll('#modelExperienceModal input[type="number"]');
    
    for (let input of inputs) {
        const value = parseFloat(input.value);
        if (isNaN(value)) {
            throw new Error(`${input.placeholder} 的值无效`);
        }
        data[input.id] = value;
    }
    
    return data;
}

// 开始预测
async function predictModel() {
    if (!currentModelType) {
        showError('请先选择一个模型');
        return;
    }
    
    try {
        showLoading(true);
        
        const formData = collectFormData();
        const config = modelConfigs[currentModelType];
        
        // 构造API请求数据
        const today = new Date();
        const dateStr = `${String(today.getDate()).padStart(2, '0')}-${String(today.getMonth() + 1).padStart(2, '0')}-${today.getFullYear()}`;
        const requestData = {
            date: dateStr,
            time: `${String(formData.hour).padStart(2, '0')}:00:00`,
            s1_temp: formData.temp1,
            s2_temp: formData.temp2,
            s3_temp: formData.temp3,
            s4_temp: formData.temp4,
            s1_light: formData.light1,
            s2_light: formData.light2,
            s3_light: formData.light3,
            s4_light: formData.light4,
            s1_sound: formData.sound1,
            s2_sound: formData.sound2,
            s3_sound: formData.sound3,
            s4_sound: formData.sound4,
            s5_co2: formData.co2,
            s5_co2_slope: 0.1, // 默认值
            s6_pir: formData.pir,
            s7_pir: formData.occupancy || 0 // 使用occupancy作为第二个PIR传感器
        };
        
        console.log('发送预测请求:', requestData);
        
        const response = await fetch(config.endpoint, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(requestData)
        });
        
        if (!response.ok) {
            throw new Error(`请求失败: ${response.status}`);
        }
        
        const result = await response.json();
        console.log('预测结果:', result);
        
        // 处理API响应格式
        let processedResult;
        if (result.success && result.data) {
            processedResult = result.data;
        } else if (result.success) {
            processedResult = result;
        } else {
            throw new Error(result.error || '预测失败');
        }
        
        displayResult(processedResult);
        
    } catch (error) {
        console.error('预测过程中出现错误:', error);
        showError(error.message);
    } finally {
        showLoading(false);
    }
}

// 显示结果
function displayResult(result) {
    const resultSection = document.getElementById('resultSection');
    const resultDisplay = document.getElementById('predictionResult');
    
    if (!resultSection || !resultDisplay) {
        console.error('结果显示元素未找到');
        return;
    }
    
    let html = '';
    
    if (currentModelType === 'ensemble') {
        // 集成模型结果
        html = `
            <div class="prediction-value">
                集成预测结果: ${result.ensemble_prediction !== undefined ? 
                    `${result.ensemble_prediction} 人` : '计算中...'}
            </div>
            <div class="ensemble-results">
                <div class="model-result">
                    <h5>随机森林</h5>
                    <div class="value">${result.rf_prediction !== undefined ? 
                        `${result.rf_prediction} 人` : '--'}</div>
                </div>
                <div class="model-result">
                    <h5>XGBoost</h5>
                    <div class="value">${result.xgb_prediction !== undefined ? 
                        `${result.xgb_prediction} 人` : '--'}</div>
                </div>
                <div class="model-result">
                    <h5>LSTM</h5>
                    <div class="value">${result.lstm_prediction !== undefined ? 
                        `${result.lstm_prediction} 人` : '--'}</div>
                </div>
            </div>
        `;
    } else {
        // 单个模型结果
        const prediction = result.prediction || result.rounded_prediction;
        const rounded = result.rounded_prediction;
        
        html = `
            <div class="prediction-value">
                预测结果: ${rounded !== undefined ? 
                    `${rounded} 人` : '计算失败'}
            </div>
            <p>详细预测值: ${prediction !== undefined ? 
                prediction.toFixed(2) : '--'}</p>
            <p>四舍五入后: ${rounded !== undefined ? 
                `${rounded} 人` : '--'}</p>
        `;
    }
    
    resultDisplay.innerHTML = html;
    resultSection.style.display = 'block';
    
    // 滚动到结果区域
    setTimeout(() => {
        resultSection.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }, 300);
}

// 显示错误
function showError(message) {
    const resultSection = document.getElementById('resultSection');
    const resultDisplay = document.getElementById('predictionResult');
    
    if (resultDisplay) {
        resultDisplay.innerHTML = `
            <div style="color: #ef4444; font-weight: 600;">
                预测失败: ${message}
            </div>
        `;
    }
    
    if (resultSection) {
        resultSection.style.display = 'block';
    }
}

// 显示加载状态
function showLoading(show) {
    const button = document.querySelector('.predict-btn');
    const buttonText = button?.querySelector('.btn-text');
    const spinner = button?.querySelector('.loading-spinner');
    
    if (button && buttonText && spinner) {
        if (show) {
            button.disabled = true;
            buttonText.textContent = '预测中...';
            spinner.style.display = 'inline-block';
        } else {
            button.disabled = false;
            buttonText.textContent = '开始预测';
            spinner.style.display = 'none';
        }
    }
}

// 隐藏结果
function hideResult() {
    const resultSection = document.getElementById('resultSection');
    if (resultSection) {
        resultSection.style.display = 'none';
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOMContentLoaded - 初始化模型体验模态框');
    initModelExperienceModal();
});

// 也在页面完全加载后再次确保初始化
window.addEventListener('load', function() {
    console.log('Window load - 确保模型体验模态框已初始化');
    if (!window.ModelExperienceModal) {
        initModelExperienceModal();
    }
}); 